package java_0616_outputstream;

import org.junit.jupiter.api.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class FileOutputStream01 {
    public static void main(String[] args) {

    }

    @Test
    public void writeFile() {
        //创建FileOutputStream对象
        String filePath = "e:\\a.txt";
        FileOutputStream fileOutputStream = null;

        try {
            //得到fileOutputStream对象,append默认为true,即在原先文件上继续写入
            fileOutputStream = new FileOutputStream(filePath, true);

            //写入一个字节
//            int num = Integer.parseInt("65");只能将数字字符串转换为数字
//            int i = Integer.valueOf('H');要得到字母的ASCII码，应该传入char类型，单引号包围
//            双引号String类型不能转为单引号char类型，cannot cast 'java.lang.String' to 'char'
            fileOutputStream.write('H');


            //写入字符串，str.getBytes()可以把字符串->字节数组
            String str = "hello,word";
            fileOutputStream.write(str.getBytes(StandardCharsets.UTF_8));


            //字节数组按长度写入
            fileOutputStream.write(str.getBytes(StandardCharsets.UTF_8), 0, 3);


        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
